<template>
  <div class="drawer-container">
    <el-drawer
      :title="drawerForm.id ? '修改货物信息' : '添加货物信息'"
      :visible.sync="drawerFormVisible"
      :wrapper-closable="false"
      size="40%"
      style="height: 100%"
      :before-close="cancel"
    >
      <el-form
        ref="drawerForm"
        label-width="130px"
        size="small"
        :model="drawerForm"
      >
        <!-- 货物名称 -->
        <el-form-item prop="name" label="货物名称">
          <el-input
            v-model="drawerForm.name"
            autocomplete="off"
            style="width: 70%"
          />
        </el-form-item>

        <!-- 货物规格 -->
        <el-form-item label="货物规格">
          <el-tag
            v-for="(label, $index) in drawerForm.labels"
            :key="label.id"
            closable
            :disable-transitions="false"
            @close="handleClose($index)"
          >
            {{ label.name }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
          >+ New Tag</el-button>
        </el-form-item>

        <!-- 获取参数（品牌、单位） -->
        <el-form-item label="货物参数">
          <!-- 品牌 -->
          <el-select
            v-model="drawerForm.brand"
            placeholder="品牌"
            style="width: 27%"
            filterable
          >
            <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.name"
              :value="brand.id"
            />
          </el-select>
          <!-- 单位 -->
          <el-select
            v-model="drawerForm.unit"
            placeholder="单位"
            style="width: 27%; margin-left: 2%"
            filterable
          >
            <el-option
              v-for="unit in units"
              :key="unit.id"
              :label="unit.name"
              :value="unit.id"
            />
          </el-select>
        </el-form-item>

        <!-- 默认进价 -->
        <el-form-item label="默认进价">
          <el-input-number
            v-model="drawerForm.inPrice"
            :precision="2"
            :step="100.0"
          />
        </el-form-item>

        <!-- 默认出价 -->
        <el-form-item label="默认出价">
          <el-input-number
            v-model="drawerForm.outPrice"
            :precision="2"
            :step="100.0"
          />
        </el-form-item>

        <!-- 仓库-分区-库位三级联动 -->
        <el-form-item label="默认存储">
          <!-- 仓库 -->
          <el-select
            v-model="drawerForm.warehouse"
            placeholder="默认仓库"
            style="width: 27%"
            filterable
            @change="getA2List"
          >
            <el-option
              v-for="warehouse in warehouses"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
          <!-- 分区 -->
          <el-select
            v-model="drawerForm.warehouseArea"
            placeholder="默认库位"
            style="width: 27%; margin-left: 2%"
            filterable
            @change="getA3List"
          >
            <el-option
              v-for="warehouse in areas"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
          <!-- 库位 -->
          <el-select
            v-model="drawerForm.warehousePosition"
            placeholder="默认分区"
            style="width: 27%; margin-left: 2%"
            filterable
          >
            <el-option
              v-for="warehouse in positions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <!-- 照片墙，上传货物照片 -->
        <el-form-item prop="image" label="货物照片">
          <el-upload
            action="dev-api/admin/product/fileUpload"
            list-type="picture-card"
            :on-remove="handleRemove"
            :file-list="drawerForm.images"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </el-upload>
        </el-form-item>

        <!-- 货物状态 -->
        <el-form-item prop="flag" label="货物状态">
          <el-radio v-model="drawerForm.flag" :label="true">启用</el-radio>
          <el-radio v-model="drawerForm.flag" :label="false">禁用</el-radio>
        </el-form-item>

        <!-- 备注内容 -->
        <el-form-item prop="others" label="备注内容">
          <el-input
            v-model="drawerForm.others"
            type="textarea"
            autocomplete="off"
            style="width: 70%"
            rows="3"
          />
        </el-form-item>

        <!-- 按钮 -->
        <el-row style="text-align: right; margin: 50px 30px 10px 0px">
          <el-button size="small" @click="cancel">取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="confirm"
          >确认</el-button>
        </el-row>
      </el-form></el-drawer>
  </div>
</template>

<script>
export default {
  name: 'Drawer',
  data() {
    return {
      // 控制弹框的显示与隐藏
      drawerFormVisible: false,
      // 存放表单数据
      drawerForm: {
        id: '',
        name: '',
        labels: [],
        images: [],
        brand: '',
        unit: '',
        inPrice: 0,
        outPrice: 0,
        warehouse: '',
        warehouseArea: '',
        warehousePosition: '',
        flag: true,
        others: '无'
      },
      inputVisible: false,
      inputValue: '',
      // 品牌信息
      brands: [],
      // 单位信息
      units: [],
      // 仓库信息
      warehouses: [],
      // 分区信息
      areas: [],
      // 库位信息
      positions: []
    }
  },
  mounted() {
    // 获取仓库
    this.getA1List()
    // 获取品牌列表
    this.getBrand()
    // 获取单位列表
    this.getUnit()
  },
  methods: {
    // 重置表单并显示弹窗
    async drawerFormOn() {
      // 显示表单
      this.drawerFormVisible = true
      // 重置表单
      this.$nextTick(() => {
        // resetFields只能重置添加了prop属性的数据
        Object.assign(this.$data.drawerForm, this.$options.data().drawerForm)
        // 重置其它列表信息
        this.labels = []
        this.warehouseArea = []
        this.warehousePosition = []
      })
    },
    // 关闭弹窗
    async drawerFormOff() {
      // 关闭（隐藏）弹窗
      this.drawerFormVisible = false
    },
    // 添加|修改单位信息
    async add() {
      // 添加单位信息
      if (!this.drawerForm.id) {
        const response = await this.$API.goods.add(this.drawerForm)
        if (response.code === 200) {
          // 成功提醒
          this.$message.success('货物信息添加成功！')
          // 关闭弹窗
          this.drawerFormOff()
          // 通知父组件，重新拉取货物信息
          this.$emit('getList')
        } else {
          // 失败提醒
          this.$message.error(response.msg)
        }
      } else {
        // 修改货物信息
        const response = await this.$API.goods.modify(this.drawerForm)
        if (response.code === 200) {
          // 成功提醒
          this.$message.success('货物信息修改成功！')
          // 关闭弹窗
          this.drawerFormOff()
          // 通知父组件，重新拉取货物信息
          this.$emit('getList')
        } else {
          // 失败提醒
          this.$message.error(response.msg)
        }
      }
    },
    // 文件上传成功
    handleAvatarSuccess(res, file) {
      // 存储上传成功
      const image = {
        'url': res.data
      }
      // 添加到图片列表中
      this.drawerForm.images.push(image)
    },
    // 文件上传前
    beforeAvatarUpload(file) {
      // 验证文件格式
      const isType = (file.type === 'image/jpeg') || (file.type === 'image/png')
      // 验证文件大小
      const isSize = file.size / 1024 / 1024 < 2

      // 异常弹窗提醒
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isSize) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isType && isSize
    },
    // 取消添加|修改
    cancel() {
      this.$confirm('是否取消【货物信息】的' + (this.drawerForm.id ? '修改' : '添加') + '？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认取消
        this.drawerFormVisible = false
      }).catch(() => {
        // 取消取消
      })
    },
    // 确认添加|修改
    confirm() {
      this.$confirm('是否确定【货物信息】的' + (this.drawerForm.id ? '修改' : '添加') + '？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认添加|修改，调用接口
        this.add()
        // 保存成功，关闭抽屉
        this.drawerFormVisible = false
      }).catch(() => {
        // 取消添加
      })
    },
    // 仓库数据
    async getA1List() {
      // 调用接口
      const response = await this.$API.goods.getWarehouse()
      if (response.code === 200) {
        this.warehouses = response.data
      } else {
        this.$message.error(response.msg)
      }
    },
    // 分区数据
    async getA2List() {
      // 调用接口
      const response = await this.$API.goods.getArea(this.drawerForm.warehouse)
      // 保存数据
      if (response.code === 200) {
        this.areas = response.data
        // 清空数据
        this.positions = []
        this.drawerForm.warehouseArea = ''
        this.drawerForm.warehousePosition = ''
      } else {
        this.$message.error(response.msg)
      }
    },
    // 库位数据
    async getA3List() {
      // 调用接口
      const response = await this.$API.goods.getPosition(this.drawerForm.warehouseArea)
      if (response.code === 200) {
        // 保存数据
        this.positions = response.data
        // 清空数据
        this.drawerForm.warehousePosition = ''
      } else {
        this.$message.error(response.msg)
      }
    },
    // 移除照片
    handleRemove(file, fileList) {
      // 从图片列表中移除该图片
      this.drawerForm.images.pop(file)
    },
    // 关闭tag
    handleClose($index) {
      this.drawerForm.labels.splice($index, 1)
    },
    // 切换input与tag状态
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加tag
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        // 构造label对象
        const obj = {
          // bug-fixed：不能添加id属性，否则会因重复报错
          name: this.inputValue.trim()
        }
        this.drawerForm.labels.push(obj)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 获取品牌信息
    async getBrand() {
      const response = await this.$API.goods.getBrand()
      if (response.code === 200) {
        this.brands = response.data
      } else {
        this.$message.error(response.msg)
      }
    },
    // 货物单位信息
    async getUnit() {
      const response = await this.$API.goods.getUnit()
      if (response.code === 200) {
        this.units = response.data
      } else {
        this.$message.error(response.msg)
      }
    }
  }
}
</script>

// 解决ElementUI超高后不显示的问题
<style>
.el-drawer__body {
  overflow: auto;
}
.el-drawer__container ::-webkit-scrollbar {
  display: none;
}
</style>

// tag与input框样式
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

